---
title: 'Overview of Node Events in Cypress'
description: 'Node event hooks enable you to tap into, modify, or extend the internal behavior of Cypress.'
sidebar_label: Overview
sidebar_position: 10
---

<ProductHeading product="app" />

# Node Events Overview

Node event hooks enable you to tap into, modify, or extend the internal behavior of
Cypress.

Normally, as a user, all of your test code, your application, and Cypress
commands are executed in the browser. But Cypress is also a Node process that
can be used to change the behavior of Cypress or to expose [plugins](/app/plugins/plugins-list) for others to consume.

> `setupNodeEvents` enables you to tap into the Node process running outside of the
> browser.

Node event hooks are a "seam" for you to write your own custom code that executes during
particular stages of the Cypress lifecycle.

## setupNodeEvents

The [`setupNodeEvents`](/app/references/configuration#setupNodeEvents)
function receives 2
arguments: [`on`](#on) and [`config`](#config). It can return a synchronous
value or can also return a Promise, which will be awaited until it resolves.
This enables you to perform asynchronous actions such as reading files in from
the filesystem.

If you return or resolve with an object, Cypress will then merge this object
into the `config` which enables you to overwrite configuration or environment
variables.

:::cypress-config-plugin-example

```ts
// configure plugins here
```

:::

### on

`on` is a function that you will use to register listeners on various **events**
that Cypress exposes.

Registering to listen on an event looks like this:

:::cypress-config-plugin-example

```ts
on('<event>', (arg1, arg2) => {
  // plugin stuff here
})
```

:::

#### List of events

Each event documents its own argument signature.

| Event                                                          | Description                                                                     |
| -------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| [`after:run`](/api/node-events/after-run-api)                  | Occurs after the run is finished.                                               |
| [`after:screenshot`](/api/node-events/after-screenshot-api)    | Occurs after a screenshot is taken.                                             |
| [`after:spec`](/api/node-events/after-spec-api)                | Occurs after a spec is finished running.                                        |
| [`before:browser:launch`](/api/node-events/browser-launch-api) | Occurs immediately before launching a browser.                                  |
| [`before:run`](/api/node-events/before-run-api)                | Occurs before the run starts.                                                   |
| [`before:spec`](/api/node-events/before-spec-api)              | Occurs when a spec is about to be run.                                          |
| [`file:preprocessor`](/api/node-events/preprocessors-api)      | Occurs when a spec or spec-related file needs to be transpiled for the browser. |
| [`task`](/api/commands/task)                                   | Occurs in conjunction with the `cy.task` command.                               |

### config

`config` is the resolved
[Cypress configuration](/app/references/configuration) of the opened project.

This configuration contains all of the values that get passed into the browser
for your project.

Some plugins may utilize or require these values, so they can take certain
actions based on the configuration. If these values are programmatically
modified, Cypress will use the new values.

:::caution

The `config` object also includes the following extra values that are not part
of the standard configuration. **These values are read only and cannot be
modified from the plugins file.**

- `configFile`: The absolute path to the
  [Cypress configuration file](/app/references/configuration). See the
  [--config-file](/app/references/command-line#cypress-open) and
  [configFile](/app/references/module-api) docs for more information on this
  value.
- `projectRoot`: The absolute path to the root of the project (e.g.
  `/Users/me/dev/my-project`)
- `version`: The version number of Cypress. This can be used to handle breaking
  changes.

:::

[Please check out our API docs for modifying configuration here.](/api/node-events/configuration-api)

## Use Cases

### Configuration

Hooking into node events allows you to programmatically alter the resolved configuration and
environment variables that come from the
[Cypress configuration file](/app/references/configuration),
[`cypress.env.json`](/app/references/environment-variables#Option-2-cypressenvjson),
the [command line](/app/references/command-line), or system environment
variables.

This enables you to do things like:

- Use multiple environments with their own configurations
- Swap out environment variables based on an environment
- Read in configuration files using the built in `fs` lib
- Change the list of browsers used for testing
- Write your configuration in `yml`

Check out our [Configuration API docs](/api/node-events/configuration-api) which
describe how to use this event.

### Preprocessors

The event `file:preprocessor` is used to customize how your test code is
transpiled and sent to the browser. By default, Cypress handles ES2015+,
TypeScript, and CoffeeScript, using webpack to package it for the browser.

You can use the `file:preprocessor` event to do things like:

- Add the latest ES\* support.
- Write your test code in ClojureScript.
- Customize the Babel settings to add your own plugins.
- Customize the options for compiling TypeScript.
- Swap out Webpack for Vite or anything else.

Check out our [File Preprocessor API docs](/api/node-events/preprocessors-api) which
describe how to use this event.

### Run Lifecycle

The events [`before:run`](/api/node-events/before-run-api) and
[`after:run`](/api/node-events/after-run-api) occur before and after a run,
respectively.

You can use [`before:run`](/api/node-events/before-run-api) to do things like:

- Set up reporting on a run
- Start a timer for the run to time how long it takes

You can use [`after:run`](/api/node-events/after-run-api) to do things like:

- Finish up reporting on a run set up in `before:run`
- Stop the timer for the run set up in `before:run`

### Spec Lifecycle

The events [`before:spec`](/api/node-events/before-spec-api) and
[`after:spec`](/api/node-events/after-spec-api) run before and after a single spec
is run, respectively.

You can use [`before:spec`](/api/node-events/before-spec-api) to do things like:

- Set up reporting on a spec running
- Start a timer for the spec to time how long it takes

You can use [`after:spec`](/api/node-events/after-spec-api) to do things like:

- Finish up reporting set up in `before:spec`
- Stop the timer for the spec set up in `before:spec`
- Delete the video recorded for the spec. This prevents it from taking time and
  computing resources for compressing and uploading the video. You can do this
  conditionally based on the results of the spec, such as if it passes (so
  videos for failing tests are preserved for debugging purposes).

Check out the [Before Spec API doc](/api/node-events/before-spec-api) and
[After Spec API doc](/api/node-events/after-spec-api) which describe how to use
these events.

### Browser Launching

The event `before:browser:launch` can be used to modify the launch arguments for
each particular browser.

You can use the `before:browser:launch` event to do things like:

- Load a Chrome extension
- Enable or disable experimental chrome features
- Control which Chrome components are loaded

Check out our [Browser Launch API docs](/api/node-events/browser-launch-api) which
describe how to use this event.

### Screenshot handling

The event `after:screenshot` is called after a screenshot is taken and saved to
disk.

You can use the `after:screenshot` event to do things like:

- Save details about the screenshot
- Rename the screenshot
- Manipulate the screenshot image by resizing or cropping it

Check out our [After Screenshot API docs](/api/node-events/after-screenshot-api)
which describe how to use this event.

### cy.task

The event `task` is used in conjunction with the
[`cy.task()`](/api/commands/task) command. It allows you to write arbitrary code
in Node to accomplish tasks that aren't possible in the browser.

You can use the `task` event to do things like:

- Manipulating a database (seeding, reading, writing, etc.)
- Storing state in Node that you want persisted (since the driver is fully
  refreshed on visits)
- Performing parallel tasks (like making multiple http requests outside of
  Cypress)
- Running an external process (like spinning up a Webdriver instance of another
  browser like Safari or puppeteer)

## Execution context

The [`setupNodeEvents`](/app/references/configuration#setupNodeEvents)
function is invoked
when Cypress opens a project.

Cypress does this by spawning an independent `child_process` which then
`requires` the [Cypress configuration file](/app/references/configuration).
This is similar to the way Visual Studio Code or Atom works.

This code will be executed using the Node version that launched Cypress.

### npm modules

When Cypress executes the
[`setupNodeEvents`](/app/references/configuration#setupNodeEvents) function
it will execute with
`process.cwd()` set to your project's path. Additionally - you will be able to
`require` **any node module** you have installed, including local files inside
your project.

For example, if your `package.json` looked like this:

```json
{
  "name": "My Project",
  "dependencies": {
    "debug": "x.x.x"
  },
  "devDependencies": {
    "lodash": "x.x.x"
  }
}
```

Then you could do any of the following in your `setupNodeEvents` function:

:::cypress-config-plugin-example

```ts
const _ = require('lodash') // yup, dev dependencies
const path = require('path') // yup, core node library
const debug = require('debug') // yup, dependencies
const User = require('./lib/models/user') // yup, relative local modules

console.log(__dirname) // /Users/janelane/Dev/my-project
console.log(process.cwd()) // /Users/janelane/Dev/my-project
```

:::

## Error handling

The [Cypress configuration file](/app/references/configuration) is loaded in
its own child process so it is isolated away from the context that Cypress
itself runs in. That means you cannot accidentally modify or change Cypress's
own execution in any way.

If your [`setupNodeEvents`](/app/references/configuration#setupNodeEvents)
function has an
uncaught exception, an unhandled rejection from a promise, or a syntax error -
Cypress will automatically catch those and display them to you inside of the
console and even in Cypress itself.

Errors in your `setupNodeEvents` function _will not crash_ Cypress.

## File changes

Normally when writing code in Node, you typically have to restart the process
after changing any files.

Cypress automatically watches your
[Cypress configuration file](/app/references/configuration) and any changes
made will take effect immediately. We will read the file in and execute the
exported function again.

This enables you to iterate on plugin code even with Cypress already running.

## <Icon name="graduation-cap" /> Real World Example

The <Icon name="github" inline="true" contentType="rwa" /> uses
[tasks](/api/commands/task) to re-seed its database, and to filter/find test
data for various testing scenarios.

<WarningSetupNodeEvents />

:::cypress-config-plugin-example

```ts
on('task', {
  async 'db:seed'() {
    // seed database with test data
    const { data } = await axios.post(`${testDataApiEndpoint}/seed`)
    return data
  },

  // fetch test data from a database (MySQL, PostgreSQL, etc...)
  'filter:database'(queryPayload) {
    return queryDatabase(queryPayload, (data, attrs) =>
      _.filter(data.results, attrs)
    )
  },
  'find:database'(queryPayload) {
    return queryDatabase(queryPayload, (data, attrs) =>
      _.find(data.results, attrs)
    )
  },
})
```

:::

:::note

_<Icon name="github" /> Source:
[Real World App > cypress.config.ts](https://github.com/cypress-io/cypress-realworld-app/blob/develop/cypress.config.ts)_

:::

Check out the
[Real World App test suites](https://github.com/cypress-io/cypress-realworld-app/tree/develop/cypress/tests/ui)
to see these tasks in action.
